<?php

namespace App\Http\Controllers\Api;

use App\UserWallet;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use App\Model\UserModel;
use App\Model\UserWalletModel;
use Illuminate\Support\Facades\Hash;
use App\Model\RechargeModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class PayController extends Controller
{
	//微信参数
	protected $config_w = [
		'appid' => 'wx6eb9737ab6756023', // APP APPID
		'app_id' => 'wx4030c295a0acf6c9', // 公众号 APPID
//      'miniapp_id' => 'wxb3fxxxxxxxxxxx', // 小程序 APPID
		'mch_id' => '1592678011',
		'key' => 'ZY2OLJCljhFS8fKQUon9b2095ezAUrsg',
		'notify_url' => 'https://api.xingqiao.cn/api/pay/wechat_notify',
		'log' => [ // optional
			'file' => 'logs/wechat.log',
			'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
			'type' => 'single', // optional, 可选 daily.
			'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
		],
		'http' => [ // optional
			'timeout' => 5.0,
			'connect_timeout' => 5.0,
			// 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
		],
// 		'mode' => 'gateway', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
	];

	//支付宝参数
	protected $config = [
		'app_id' => '2021001168631299',
		'notify_url' => 'https://api.xingqiao.cn/api/pay/notify',
		'return_url' => '',
		'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkp1VUUY/vlA6WuvXU4nMVKEEajo/sWVUCe2pYLKD1oqm6r+s1MHxzmZeQdZEgRbcBOxvR87/RIFyoDouqTD3WigKVV+44dvjxPtYBr6zIz96Mzz0p6EwF6HNTjx2f0NSMh0D7pTC6crz+yLgY3WSD57E6ySMyxXZv623lwAQiybrBM7l5OA/c/e38Khv5f5sD5YUdnReZRIIzPgDoD/OI0TitD2pQT+TE9OZhczWKW2kJjA65xaFEwTo8aM8ctt/MVR/SPSSPk4qk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dt0M/ab5/R1xT79dCoYRsDNpz+PWIxneFXrp4hs5fTkSeNCJpU93DNLFk2T5f4BQ7fLOaL92fdYeJhr6t60l/sYg+9ONqFrfV4pwwKBgEv5hbL2h0jTdAXAwzf7HQd5s5ZAQGbOVnoaENQWX0nvWehOkbn3arLiwL/zzxiaZlMPjo5O6GJxS5spIoMf1xLETd40ZfTSMtTR3EfcpwVC8XeDACMGJBr+gvsehT8i7/MBCh0ll+xzsoQh4v5L015MVu14qTdoRmuhruNeR2IpAoGAOutgkDM0WUMDlTb6ZoIUoDxR/JDuJ2aWznsNZJ/oNzwMN5quGKiinX1dhWulPAhymWl+9oH3JBJXsTccdvj6nZWqSOO4flhO1a9nFAmk5b2gH8mDiwtoN/SrWVFIU6piVNS41ju3lqyP/YmSpQrdP0BvuRGjupGu1ST6rsPl9UMCgYEAmIzXJPfOFiiBt96YEFe3qp68ILtXnd8tRpZ8Yjo4StDnl2NDfNUILFGin14wkLGRrhyUvlyW9TXZHrTKqvDomSrP6t5npCIVdEIfbRgb9NvhaXTOVP0r+NyIotF7BN6YSG3AZ2ovt9ZyX1LyAhm8G8TCWNhh5leTJYguBplmpes=',
//      // 加密方式： **RSA2**
		// 使用公钥证书模式，请配置下面两个参数，同时修改ali_public_key为以.crt结尾的支付宝公钥证书路径，如（./cert/alipayCertPublicKey_RSA2.crt）
		// 'app_cert_public_key' => './cert/appCertPublicKey.crt', //应用公钥证书路径
		// 'alipay_root_cert' => './cert/alipayRootCert.crt', //支付宝根证书路径
//      'app_id' => '2021001169603154',
//      'notify_url' => 'https://api.xingqiao.cn/api/pay/notify',
//      'return_url' => '',
//      'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkp1VUUY/vlA6WuvXU4nMVKEEajo/sWVUCe2pYLKD1oqm6r+s1MHxzmZeQdZEgRbcBOxvR87/RIFyoDouqTD3WigKVV+44dvjxPtYBr6zIz96Mzz0p6EwF6HNTjx2f0NSMh0D7pTC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namTSxPi04Hff1+v8ndxT4wC52O2MvrgRc5IwQkVuZ2mOH7Gl3hHbmqqmdLUynRH3FKdQKBgQC4XvV+eDfpTvhRq2Hnm2HrIHvMjvZPg89usUcLDWnc6k0mTOCc0QGVCAgT2heVC/PS2orrVLUvmhekqR1nZ2HJzH8BBKXp1Z/OT1OOVlGc5rW0byrbpm+YfxgLc7GuV/uGbXVz+nishiMh+5pE0h4/p01WMaQ7usFOHuzPTlveawKBgQDGpPgtnilKKRHS7E2qcjgBpumZtO4ABQvZOgsF57FU4zSwpyvr56Nv1RNe3L96+/bsISy8W4gZbIMqh4vKW8hDCCxTx8jCjV7GlAJ7Mq+yx+Xoi3NMMXBTQ+WWdkO9snS/A8Vzm6qGc269ik9qEg5ebtklbGzUTpogdo45HvIrDQKBgDMJpm/SG7gsMjV5eerBasPKBDtGQA0W8e80h/QZTHrpKV423d7LROLajFHih7Cs1FxEPzySAG4i+/SLFCaxybIxN98ySDOI/WoBL6IxZvpGK3q9Y2HWmwHd/Ov+pOscU/aMin0Gky0/HK6llbkDaXg5egEoUMxwEF7t1KQ2jtvtAoGAS0ewoNx0HJXiUW66oJZcqHpko/JnkwqUYgVTHm30t2AwUbS5z8UQGNn34gnAH26NCn9Q3FzT3WzEtUTkGqkYjOj3OqUJAjyB8HBM8HZPRdBkZDxFkow2X6dLWvcugtvPEGFXUp4QwFyyerfN28A2mdj/qXehyvgWdVRpOTzg7o0=',

		'log' => [ // optional
			'file' => 'logs/alipay.log',
			'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
			'type' => 'single', // optional, 可选 daily.
			'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
		],
		'http' => [ // optional
			'timeout' => 5.0,
			'connect_timeout' => 5.0,
			// 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
		],
//        'mode' => 'dev', // optional,设置此参数，将进入沙箱模式   dev正式
	];

	public function index()
	{
		//接收充值记录
		if(!request()->num){
			return ['code'=>0,'msg'=>retStrInfo(114)];
		}
		//生成订单
		$osn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
		DB::beginTransaction();
		try{
			$aa = RechargeModel::create([
				'uid' => request()->uid,
				'num' => request()->num,
				'sn' => $osn,
			]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		$order_sn = RechargeModel::where('id',$aa->id)->value('sn');
		$order = [
			'out_trade_no' => $order_sn,
			'total_amount' => request()->num,
			'subject' => "现金 - 充值",
		];

		$alipay = Pay::alipay($this->config);
		$res = $alipay->app($order)->getContent();
		return $this->success('',$res);
	}

	public function notify()
	{
		$alipay = Pay::alipay($this->config);
		$data = $alipay->verify();
		if (!$data) {
			return;
		}// 验证成功
		$trade_status = $data->trade_status;// 交易状态
		if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
			//此处支付成功后的业务逻辑处理根据自己需求
			$out_trade_no = $data->out_trade_no; // 订单号
			$recharge = RechargeModel::where('sn',$out_trade_no)->where('state',2)->first();
			$recharge->state = 1;
			$recharge->save();

			//增加日志
			//增加扣除日志
			UserWalletModel::handleAccount($recharge->uid,$recharge->num,'+','现金充值',1,1);
			return $alipay->success();
		}
	}



	//微信支付
	public function wechat(){

		//接收充值记录
		if(!request()->num){
			return ['code'=>0,'msg'=>retStrInfo(114)];
		}
		$osn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
		DB::beginTransaction();
		try{
			$aa = RechargeModel::create([
				'uid' => request()->uid,
				'num' => request()->num,
				'sn' => $osn,
				'type' => 2,
			]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		$order_sn = RechargeModel::where('id',$aa->id)->value('sn');
		$order = [
			'out_trade_no' => $order_sn,
			'total_fee' => request()->num * 100,
			'body' => "现金 - 充值",
		];

		$pay = Pay::wechat($this->config_w)->app($order)->getContent();
		return $this->success('',$pay);
	}

	//微信回调
	public function wechat_notify(){
		$pay = Pay::wechat($this->config_w);
		try{
			$data = $pay->verify(); // 是的，验签就这么简单！
			$order = RechargeModel::where('sn', $data->out_trade_no)->first();
			if (!$order || $order->state != 2)  {
				//如果订单状态异常直接退出
				return $pay->success();
			}
			if (($order->num) != $data->total_fee / 100) {
				//如果金额不匹配直接退出
				return $pay->success();
			}

			//进行订单状态变更等支付成功操作
			//....
			$out_trade_no = $data->out_trade_no; // 订单号
			$recharge = RechargeModel::where('sn',$out_trade_no)->where('state',2)->first();
			$recharge->state = 1;
			$recharge->save();

			//增加日志
			//增加扣除日志
			UserWalletModel::handleAccount($recharge->uid,$recharge->num,'+','现金充值',1,1);
			Log::debug('Wechat notify', $data->all());
		} catch (\Exception $e) {

		}
		return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
	}
}